import asyncio
import requests
import time
import aiohttp
import aiofiles
from config import LiveConfig
import uuid


async def get_data(key, url):
    # print('start request', key)
    connector = aiohttp.TCPConnector(verify_ssl=False)
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get(url) as resp:
            if resp.status == 200:
                try:
                    json_data = await resp.json()
                except aiohttp.client_exceptions.ContentTypeError:
                    json_data = None
                # print('end request', key)
                return json_data


async def get_image_data(key, url):
    # print('get_image_data_start', key)
    connector = aiohttp.TCPConnector(verify_ssl=False)
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get(url) as resp:
            if resp.status == 200:
                try:
                    byte_data = await resp.read()
                    # print('get_image_data_end', key)
                    # data = await save_image(key, byte_data)
                    data = await save_image_by_threading_first(key, byte_data)
                except aiohttp.client_exceptions.ContentTypeError:
                    data = None
                return data


async def save_image_by_threading_first(key, byte_data):
    print('save_image_start', key)
    _loop = asyncio.get_event_loop()
    tmp = await _loop.run_in_executor(None, save_image_by_threading_second, key, byte_data)
    print('save_image_end', key)
    return tmp


def save_image_by_threading_second(key, byte_data):
    filename = str(uuid.uuid1()) + '.jpg'
    with open(LiveConfig.SAVE_IMAGE_PATH + filename, 'wb') as f:
        f.write(byte_data)
        return filename


async def save_image(key, byte_data):
    print('save_image_start', key)
    filename = str(uuid.uuid1()) + '.jpg'
    async with aiofiles.open(LiveConfig.SAVE_IMAGE_PATH + filename, 'wb') as f:
        await f.write(byte_data)
        print('save_image_end', key)
        return filename


async def save_image1(byte_data):
    filename = str(uuid.uuid1()) + '.jpg'
    with open(filename, 'rb') as f:
        pass


loop = asyncio.get_event_loop()
get_list_cor = asyncio.ensure_future(get_data(key='get_list_page_1', url=LiveConfig.ACTION['GET_LIST'].format(1)))
loop.run_until_complete(get_list_cor)
ids = [_['info']['id'] for _ in get_list_cor.result()['data']['items']]
print(ids)
page_tasks = [asyncio.ensure_future(get_data(key='get_page_data_' + str(_), url=LiveConfig.ACTION['GET_SINGLE'].format(_))) for _ in ids]
loop.run_until_complete(asyncio.wait(page_tasks))
page_tasks_result = [_.result()['data']['images'] for _ in page_tasks]
all_images = []
for i in page_tasks_result:
    all_images = all_images + [_['img'] for _ in i]
print(all_images)
# save_image_tasks = []
# for _ in range(len(all_images)):
#     save_image_tasks.append(asyncio.ensure_future(get_image_data(key=_, url=all_images[_])))
# loop.run_until_complete(asyncio.wait(save_image_tasks))
# loop.close()
